package com.burstly.lib.util;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Debug;
import android.os.Environment;
import android.os.Looper;
import android.os.Process;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import com.burstly.lib.component.FailedToShow;
import com.burstly.lib.constants.Constants;
import com.burstly.lib.exception.WrongThreadException;
import com.burstly.lib.feature.FeatureFactory;
import com.burstly.lib.network.ResponseObject;
import com.burstly.lib.network.TimeoutManager;
import com.burstly.lib.network.beans.CreativeDataType;
import com.burstly.lib.network.beans.DestinationType;
import com.burstly.lib.network.beans.ResponseBean.ResponseData;
import com.burstly.lib.network.beans.ResponseBean.ResponseData.AdType;
import com.burstly.lib.network.beans.TextAdType;
import com.burstly.lib.network.beans.UserAgentInfo;
import com.burstly.lib.network.request.AbortableAsyncTask;
import com.burstly.lib.network.request.RequestManager;
import com.burstly.lib.network.request.RequestManager.ConnectionInfo;
import com.burstly.lib.service.ServerRequestBean;
import com.burstly.lib.util.json.IJsonProcessor;
import com.burstly.lib.util.json.JsonProcessorFactory;
import java.io.Closeable;
import java.io.File;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TimeZone;
import java.util.UUID;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpProtocolParams;

public final class Utils
{
  private static final String DEVICE_ID_KEY = "uniqueDeviceIdKey";
  private static final int EXPIRATION_DELTA = 20000;
  private static final int IO_BUFFER_SIZE = 4096;
  private static final IJsonProcessor JSON_PROCESSOR = JsonProcessorFactory.getCurrentJsonProcessor();
  private static final LoggerExt LOG = LoggerExt.getInstance();
  private static final int MRAID_FLAG_MASK = 2048;
  private static final int ORMMA_FLAG_MASK = 1024;
  private static final int OVERRIDE_HARDWARE_ACCEL_DISABLE = 8192;
  private static final List<String> READ_PHONE_STATE_PERMISSION = Arrays.asList(new String[] { "android.permission.READ_PHONE_STATE" });
  private static final String TAG = "Utils";
  private static final String THIRDPARTY_CLASS_TEMPLATE = "com.burstly.lib.component.networkcomponent.%s.%s";
  private static final String UNIQUE_DEVICE_ID = "uniqueDeviceId";
  private static Context sApplicationContext;
  private static String sCCSString;
  private static String sEncAndroidId = "";
  private static String sEncDeviceId = "";
  private static String sEncMac = "";
  private static String sMccCode = "0";
  private static String sMncCode = "0";
  private static String sRawAndroidId;
  private static String sRawDeviceId;
  private static String sRawMac;
  private static String sRawMacSha1;
  private static String sSha1DeviceId;
  private static String sUserWebClient;

  public static void abortRequestTask(AbortableAsyncTask<?> paramAbortableAsyncTask)
  {
    if (paramAbortableAsyncTask != null)
      paramAbortableAsyncTask.abortRequest();
  }

  public static void addInStackTrace(Throwable paramThrowable, String paramString)
  {
    StackTraceElement[] arrayOfStackTraceElement1 = paramThrowable.getStackTrace();
    StackTraceElement[] arrayOfStackTraceElement2 = new StackTraceElement[1 + arrayOfStackTraceElement1.length];
    arrayOfStackTraceElement2[0] = new StackTraceElement(paramString, " ", null, 1);
    for (int i = 0; i < arrayOfStackTraceElement1.length; i++)
      arrayOfStackTraceElement2[(i + 1)] = arrayOfStackTraceElement1[i];
    paramThrowable.setStackTrace(arrayOfStackTraceElement2);
  }

  public static String arrayToString(Object[] paramArrayOfObject, String paramString)
  {
    StringBuilder localStringBuilder = new StringBuilder();
    int i = 0;
    int j = paramArrayOfObject.length;
    while (i < j)
    {
      localStringBuilder.append(paramArrayOfObject[i]);
      if (i + 1 != j)
        localStringBuilder.append(paramString);
      i++;
    }
    return localStringBuilder.toString();
  }

  private static String bytesToString(byte[] paramArrayOfByte)
  {
    StringBuilder localStringBuilder = new StringBuilder();
    int i = paramArrayOfByte.length;
    int j = 0;
    if (j < i)
    {
      String str = Integer.toHexString(0xFF & paramArrayOfByte[j]);
      if (str.length() == 1)
        localStringBuilder.append("0").append(str);
      while (true)
      {
        j++;
        break;
        localStringBuilder.append(str);
      }
    }
    return localStringBuilder.toString();
  }

  public static boolean canWriteToSDCard()
  {
    File localFile = Environment.getExternalStorageDirectory();
    return (Environment.getExternalStorageState().equals("mounted")) && (localFile.canWrite()) && (localFile.canRead());
  }

  public static void cancelTask(AsyncTask<?, ?, ?> paramAsyncTask)
  {
    if (paramAsyncTask != null)
      paramAsyncTask.cancel(true);
  }

  public static String capitalize(String paramString)
  {
    Object[] arrayOfObject = new Object[2];
    arrayOfObject[0] = Character.valueOf(Character.toUpperCase(paramString.charAt(0)));
    arrayOfObject[1] = paramString.substring(1);
    return String.format("%s%s", arrayOfObject);
  }

  private static boolean checkFlag(Integer paramInteger, int paramInt)
  {
    return (paramInteger != null) && ((paramInt & paramInteger.intValue()) != 0);
  }

  public static void checkIsUiThread()
    throws WrongThreadException
  {
    if (!Thread.currentThread().equals(sApplicationContext.getMainLooper().getThread()))
      throw new WrongThreadException("Code must be invoked from the UI thread");
  }

  public static void checkNotNull(Object paramObject, String paramString)
    throws IllegalArgumentException
  {
    if (paramObject == null)
      throw new IllegalArgumentException(paramString);
  }

  public static void closeStream(Closeable paramCloseable)
  {
    if (paramCloseable != null);
    try
    {
      paramCloseable.close();
      return;
    }
    catch (IOException localIOException)
    {
      LOG.logError("Utils", "Error while closing stream!", new Object[0]);
    }
  }

  public static void configureServerRequestBean(Context paramContext, ServerRequestBean paramServerRequestBean)
  {
    paramServerRequestBean.setBundleId(paramContext.getPackageName());
    paramServerRequestBean.setApplicationVersion(getApplicationVersionName());
    paramServerRequestBean.setApplicationVersionCode(getApplicationVersionCode());
    if (FeatureFactory.getCurrencyFeature() != null);
    paramServerRequestBean.setAndroidId(encryptedAndroidId(paramContext));
    paramServerRequestBean.setCarrier(getCarrier());
    paramServerRequestBean.setClientDateTime(getDateTime("yyyy-MM-dd'T'HH:mm:ss'Z'"));
    RequestManager.ConnectionInfo localConnectionInfo = RequestManager.getConnectionInfo();
    paramServerRequestBean.setConnectionType(localConnectionInfo.getCode());
    paramServerRequestBean.setConnectionTypeDetailed(localConnectionInfo.getSubtipeName());
    setScreenInfo(paramContext, paramServerRequestBean);
    paramServerRequestBean.setDevice(Build.MODEL);
    paramServerRequestBean.setDeviceFamily(Build.BRAND);
    paramServerRequestBean.setDeviceId(getDeviceId(paramContext));
    paramServerRequestBean.setIpAddress(getLocalIpAddress());
    paramServerRequestBean.setMac(getMacSha1());
    paramServerRequestBean.setMCC(getMccCode());
    paramServerRequestBean.setMNC(getMncCode());
    paramServerRequestBean.setPlatformVersion(Build.VERSION.RELEASE);
    paramServerRequestBean.setWebUserAgent(getUserAgentString(paramContext));
    paramServerRequestBean.setMraidVersion("2.0");
    paramServerRequestBean.setOrmmaVersion("1.1");
    paramServerRequestBean.setRewardsVersion("2");
  }

  public static String decrypt(String paramString1, String paramString2)
    throws Exception
  {
    return Crypto.decrypt(paramString1, paramString2);
  }

  public static String encodeUrl(String paramString)
  {
    if (paramString == null)
      return null;
    return paramString.replaceAll(" ", "%20");
  }

  public static String encryp(String paramString1, String paramString2)
    throws Exception
  {
    return Crypto.encrypt(paramString1, paramString2);
  }

  private static String encryptId(String paramString)
  {
    try
    {
      String str = Crypto.encrypt("", paramString);
      return str;
    }
    catch (Exception localException)
    {
      LOG.logError("Utils", localException.getMessage(), new Object[0]);
    }
    return "";
  }

  public static String encryptedAndroidId(Context paramContext)
  {
    try
    {
      if (sEncAndroidId.length() == 0)
      {
        String str2 = getRawAndroidId(paramContext);
        if (str2 == null)
          break label37;
        sEncAndroidId = encryptId(str2);
      }
      while (true)
      {
        String str1 = sEncAndroidId;
        return str1;
        label37: LOG.logWarning("Utils", "Current android id is null, could not encrypt id.", new Object[0]);
      }
    }
    finally
    {
    }
  }

  public static String encryptedDeviceId(Context paramContext)
  {
    try
    {
      if ((ManifestValidator.customValidate(null, READ_PHONE_STATE_PERMISSION, null).getMandatoryPermissions().isEmpty()) && (sEncDeviceId.length() == 0))
      {
        TelephonyManager localTelephonyManager = (TelephonyManager)paramContext.getSystemService("phone");
        String str2 = null;
        if (localTelephonyManager != null)
          str2 = localTelephonyManager.getDeviceId();
        if (str2 == null)
          break label82;
        sEncDeviceId = encryptId(str2);
      }
      while (true)
      {
        String str1 = sEncDeviceId;
        return str1;
        label82: LOG.logWarning("Utils", "Current device id is null, could not encrypt id.", new Object[0]);
      }
    }
    catch (PackageManager.NameNotFoundException localNameNotFoundException)
    {
      while (true)
        LOG.logDebug("Utils", Log.getStackTraceString(localNameNotFoundException), new Object[0]);
    }
    finally
    {
    }
  }

  public static String encryptedMac()
  {
    try
    {
      if (sEncMac.length() == 0)
      {
        String str2 = getRawMac(sApplicationContext);
        sEncMac = encryptId(str2);
        if (sEncMac == null)
          sEncMac = str2;
      }
      String str1 = sEncMac;
      return str1;
    }
    finally
    {
    }
  }

  public static String extractFactoryClassName(String paramString)
  {
    return getClassName(paramString, "AdaptorFactory");
  }

  private static Bitmap fetchBitmap(String paramString)
    throws MalformedURLException, IOException
  {
    URLConnection localURLConnection = new URL(paramString.replace(" ", "%20")).openConnection();
    localURLConnection.setUseCaches(true);
    if (sApplicationContext != null)
      localURLConnection.setRequestProperty("User-Agent", getUserAgentString(sApplicationContext));
    localURLConnection.connect();
    FlushedInputStream localFlushedInputStream = new FlushedInputStream(localURLConnection.getInputStream());
    Bitmap localBitmap = BitmapFactory.decodeStream(localFlushedInputStream);
    localFlushedInputStream.close();
    return localBitmap;
  }

  private static String filterColor(String paramString)
  {
    if (paramString.startsWith("#"))
      return paramString;
    if ((paramString.startsWith("0x")) || (paramString.startsWith("0X")))
      return "#" + paramString.substring(2);
    return "#" + paramString;
  }

  public static Boolean forceHardwareAccelerationTo(ResponseBean.ResponseData paramResponseData)
  {
    ResponseBean.ResponseData.AdType localAdType = paramResponseData.getAdType();
    if ((localAdType != null) && (checkFlag(localAdType.getExtendedProperty(), 8192)));
    for (int i = 1; i != 0; i = 0)
      return Boolean.valueOf(false);
    return null;
  }

  public static ResponseObject fromJson(String paramString)
  {
    return JSON_PROCESSOR.fromJson(paramString);
  }

  public static <T> T fromJson(String paramString, Class<T> paramClass)
  {
    return JSON_PROCESSOR.fromJson(paramString, paramClass);
  }

  public static List<String> fromJsonToListOfStrings(String paramString)
  {
    return JSON_PROCESSOR.fromJsonToListOfStrings(paramString);
  }

  public static String generateUID()
  {
    String str = UUID.randomUUID().toString();
    return str.substring(-8 + str.length(), str.length());
  }

  private static String generateUniqueId(Context paramContext)
  {
    SharedPreferences localSharedPreferences = paramContext.getApplicationContext().getSharedPreferences("uniqueDeviceId", 0);
    String str1 = localSharedPreferences.getString("uniqueDeviceIdKey", "");
    if (!str1.equals(""))
      return str1;
    String str2 = UUID.randomUUID().toString();
    if (!localSharedPreferences.edit().putString("uniqueDeviceIdKey", str2).commit())
      LOG.logError("Utils", "Can not save unique device id in preferences! Your device will not be tracked on server.", new Object[0]);
    return str2;
  }

  public static String get3rdPartySdkName(String paramString)
  {
    int i = paramString.indexOf('?');
    if (i != -1)
      return paramString.substring(0, i);
    return "";
  }

  public static String get3rdPartySdkParams(String paramString)
  {
    int i = paramString.indexOf('{');
    if (i != -1)
      return paramString.substring(i, paramString.length());
    return "";
  }

  public static String getAppPackage(Context paramContext)
  {
    PackageManager localPackageManager = paramContext.getPackageManager();
    try
    {
      String str = localPackageManager.getPackageInfo(paramContext.getPackageName(), 0).packageName;
      return str;
    }
    catch (PackageManager.NameNotFoundException localNameNotFoundException)
    {
      LOG.logError("Utils", "Could not get package name.", new Object[0]);
    }
    return "";
  }

  public static Context getApplicationContext()
  {
    return sApplicationContext;
  }

  public static int getApplicationVersionCode()
  {
    PackageManager localPackageManager = sApplicationContext.getPackageManager();
    try
    {
      int i = localPackageManager.getPackageInfo(sApplicationContext.getPackageName(), 0).versionCode;
      return i;
    }
    catch (PackageManager.NameNotFoundException localNameNotFoundException)
    {
      LOG.logWarning("Utils", localNameNotFoundException.getMessage(), new Object[0]);
    }
    return 0;
  }

  public static String getApplicationVersionName()
  {
    PackageManager localPackageManager = sApplicationContext.getPackageManager();
    try
    {
      String str = localPackageManager.getPackageInfo(sApplicationContext.getPackageName(), 0).versionName;
      return str;
    }
    catch (PackageManager.NameNotFoundException localNameNotFoundException)
    {
      LOG.logWarning("Utils", localNameNotFoundException.getMessage(), new Object[0]);
    }
    return "";
  }

  public static Bitmap getBitmapByUrl(String paramString)
  {
    try
    {
      Bitmap localBitmap = fetchBitmap(paramString);
      return localBitmap;
    }
    catch (MalformedURLException localMalformedURLException)
    {
      LOG.logError("Utils", "Url for image is malformed: {0}", new Object[] { paramString });
      return null;
    }
    catch (IOException localIOException)
    {
      while (true)
        LOG.logError("Utils", "Connection problems. Could not load image from url: {0}", new Object[] { paramString });
    }
    catch (Exception localException)
    {
      while (true)
      {
        LOG.logError("Utils", "Error appeared when fetching bitmap from {0}", new Object[] { paramString });
        LOG.logThrowable("Utils", localException);
      }
    }
  }

  public static String getCCSString()
  {
    return sCCSString;
  }

  public static String getCarrier()
  {
    TelephonyManager localTelephonyManager = (TelephonyManager)sApplicationContext.getSystemService("phone");
    if (localTelephonyManager != null)
    {
      String str = localTelephonyManager.getNetworkOperatorName();
      if (str != null)
        return str;
    }
    return "";
  }

  private static String getClassName(String paramString1, String paramString2)
  {
    return String.format("com.burstly.lib.component.networkcomponent.%s.%s", new Object[] { paramString1, capitalize(paramString1) + paramString2 });
  }

  private static HttpClient getClient()
  {
    try
    {
      KeyStore localKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
      localKeyStore.load(null, null);
      BurstlySSLSocketFactory localBurstlySSLSocketFactory = new BurstlySSLSocketFactory(localKeyStore);
      localBurstlySSLSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
      BasicHttpParams localBasicHttpParams2 = new BasicHttpParams();
      HttpProtocolParams.setVersion(localBasicHttpParams2, HttpVersion.HTTP_1_1);
      HttpProtocolParams.setContentCharset(localBasicHttpParams2, "UTF-8");
      HttpConnectionParams.setConnectionTimeout(localBasicHttpParams2, TimeoutManager.getConnectTimeout());
      HttpConnectionParams.setSoTimeout(localBasicHttpParams2, TimeoutManager.getReadimeout());
      SchemeRegistry localSchemeRegistry = new SchemeRegistry();
      localSchemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
      localSchemeRegistry.register(new Scheme("https", localBurstlySSLSocketFactory, 443));
      DefaultHttpClient localDefaultHttpClient = new DefaultHttpClient(new SingleClientConnManager(localBasicHttpParams2, localSchemeRegistry), localBasicHttpParams2);
      return localDefaultHttpClient;
    }
    catch (Exception localException)
    {
      BasicHttpParams localBasicHttpParams1 = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(localBasicHttpParams1, TimeoutManager.getConnectTimeout());
      HttpConnectionParams.setSoTimeout(localBasicHttpParams1, TimeoutManager.getReadimeout());
      return new DefaultHttpClient(localBasicHttpParams1);
    }
  }

  public static Drawable getCloseImage(Context paramContext)
  {
    return getImage(paramContext, "close-button.png", false);
  }

  public static Integer getColorFromHex(String paramString)
  {
    if (paramString != null)
      try
      {
        Integer localInteger = Integer.valueOf(Color.parseColor(filterColor(paramString)));
        return localInteger;
      }
      catch (Exception localException)
      {
        LOG.logWarning("Utils", localException.getMessage(), new Object[0]);
      }
    return null;
  }

  public static CreativeDataType getDataTypeByCode(Integer paramInteger)
  {
    for (CreativeDataType localCreativeDataType : CreativeDataType.values())
      if (localCreativeDataType.getValue().equals(paramInteger))
        return localCreativeDataType;
    return null;
  }

  public static Date getDateFromString(String paramString1, String paramString2)
  {
    if (paramString1 == null)
      return null;
    try
    {
      Date localDate = new SimpleDateFormat(paramString2).parse(paramString1);
      return localDate;
    }
    catch (ParseException localParseException)
    {
      LOG.logThrowable("Utils", localParseException);
    }
    return null;
  }

  public static String getDateTime(String paramString)
  {
    SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat(paramString);
    localSimpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    return localSimpleDateFormat.format(new Date());
  }

  public static DestinationType getDestinationByCode(Integer paramInteger)
  {
    for (DestinationType localDestinationType : DestinationType.values())
      if (localDestinationType.getValue().equals(paramInteger))
        return localDestinationType;
    return DestinationType.DestinationType_unknown;
  }

  public static String getDeviceCurrentLanguage()
  {
    return Locale.getDefault().getLanguage();
  }

  public static String getDeviceId()
  {
    return getDeviceSHA1Id(sApplicationContext);
  }

  public static String getDeviceId(Context paramContext)
  {
    return getDeviceSHA1Id(paramContext);
  }

  public static String getDeviceSHA1Id(Context paramContext)
  {
    try
    {
      if (sSha1DeviceId == null)
      {
        String str2 = getRawDeviceId(paramContext);
        sSha1DeviceId = sha1(str2, str2);
        if (sSha1DeviceId == null)
          sSha1DeviceId = str2;
      }
      String str1 = sSha1DeviceId;
      return str1;
    }
    finally
    {
    }
  }

  public static String getFailedIds(Collection<FailedToShow> paramCollection)
  {
    StringBuilder localStringBuilder = new StringBuilder();
    Iterator localIterator = paramCollection.iterator();
    while (localIterator.hasNext())
    {
      localStringBuilder.append(((FailedToShow)localIterator.next()).getRvCr());
      if (localIterator.hasNext())
        localStringBuilder.append(",");
    }
    return localStringBuilder.toString();
  }

  public static int getFillparentValue()
  {
    if (Build.VERSION.SDK_INT >= 8);
    return -1;
  }

  private static Drawable getImage(Context paramContext, String paramString, boolean paramBoolean)
  {
    AssetManager localAssetManager = paramContext.getAssets();
    String str = paramString;
    InputStream localInputStream = null;
    if (paramBoolean);
    try
    {
      str = String.format(paramString, new Object[] { "108x72" });
      localInputStream = localAssetManager.open(str);
      Drawable localDrawable = Drawable.createFromStream(localInputStream, str);
      return localDrawable;
    }
    catch (IOException localIOException)
    {
      LOG.logError("Utils", "Can not find image: {0} in assets directory!", new Object[] { str });
      return null;
    }
    finally
    {
      closeStream(localInputStream);
    }
  }

  private static int getIntValue(String paramString)
    throws Exception
  {
    if (paramString != null)
      try
      {
        int i = Integer.parseInt(paramString);
        return i;
      }
      catch (NumberFormatException localNumberFormatException)
      {
        LOG.logError("Utils", "Error converting int parameter from: {0}", new Object[] { paramString });
        throw localNumberFormatException;
      }
    LOG.logDebug("Utils", "Can not convert null string to number, returning 0...", new Object[0]);
    throw new Exception();
  }

  public static Integer getIntValue(String paramString, Integer paramInteger)
  {
    try
    {
      Integer localInteger = Integer.valueOf(getIntValue(paramString));
      return localInteger;
    }
    catch (Exception localException)
    {
    }
    return paramInteger;
  }

  public static String getLocalIpAddress()
  {
    try
    {
      InetAddress localInetAddress;
      do
      {
        Enumeration localEnumeration1 = NetworkInterface.getNetworkInterfaces();
        Enumeration localEnumeration2;
        while (!localEnumeration2.hasMoreElements())
        {
          if (!localEnumeration1.hasMoreElements())
            break;
          localEnumeration2 = ((NetworkInterface)localEnumeration1.nextElement()).getInetAddresses();
        }
        localInetAddress = (InetAddress)localEnumeration2.nextElement();
      }
      while (localInetAddress.isLoopbackAddress());
      String str = localInetAddress.getHostAddress().toString();
      return str;
    }
    catch (SocketException localSocketException)
    {
      LOG.logError("Utils", localSocketException.toString(), new Object[0]);
    }
    return null;
  }

  public static String getMacSha1()
  {
    try
    {
      if (sRawMacSha1 == null)
      {
        String str2 = getRawMac(sApplicationContext);
        sRawMacSha1 = sha1(str2, str2);
        if (sRawMacSha1 == null)
          sRawMacSha1 = str2;
      }
      String str1 = sRawMacSha1;
      return str1;
    }
    finally
    {
    }
  }

  public static String getMccCode()
  {
    if (sMccCode.equals("0"))
    {
      TelephonyManager localTelephonyManager = (TelephonyManager)sApplicationContext.getSystemService("phone");
      if (localTelephonyManager != null)
      {
        String str = localTelephonyManager.getNetworkOperator();
        if ((str != null) && (str.length() >= 3))
          sMccCode = str.substring(0, 3);
      }
    }
    return sMccCode;
  }

  public static String getMncCode()
  {
    if (sMncCode.equals("0"))
    {
      TelephonyManager localTelephonyManager = (TelephonyManager)sApplicationContext.getSystemService("phone");
      if (localTelephonyManager != null)
      {
        String str = localTelephonyManager.getNetworkOperator();
        if ((str != null) && (str.length() >= 4))
          sMncCode = str.substring(3);
      }
    }
    return sMncCode;
  }

  public static int getOrientation(Context paramContext)
  {
    int i = ((WindowManager)paramContext.getSystemService("window")).getDefaultDisplay().getOrientation();
    int j = -1;
    switch (i)
    {
    default:
    case 0:
    case 1:
    case 2:
    case 3:
    }
    while (true)
    {
      LoggerExt localLoggerExt = LOG;
      Object[] arrayOfObject = new Object[1];
      arrayOfObject[0] = Integer.valueOf(j);
      localLoggerExt.logDebug("Utils", "getOrientation: {0}", arrayOfObject);
      return j;
      j = 0;
      continue;
      j = 90;
      continue;
      j = 180;
      continue;
      j = 270;
    }
  }

  public static byte[] getParamsBytes(String paramString)
  {
    try
    {
      byte[] arrayOfByte = paramString.getBytes("ASCII");
      return arrayOfByte;
    }
    catch (UnsupportedEncodingException localUnsupportedEncodingException)
    {
      LOG.logWarning("Utils", "ASCII encoding is not available! Using platform default.", new Object[0]);
    }
    return paramString.getBytes();
  }

  private static String getPhoneType(TelephonyManager paramTelephonyManager)
  {
    switch (paramTelephonyManager.getPhoneType())
    {
    default:
      return "UNKNOWN";
    case 2:
      LOG.logWarning("Utils", "This is a CDMA phone so operator name and mcc data can be invalid.", new Object[0]);
      return "CDMA";
    case 1:
      return "GSM";
    case 0:
    }
    return "NONE";
  }

  public static String getRawAndroidId(Context paramContext)
  {
    try
    {
      if (sRawAndroidId == null)
      {
        sRawAndroidId = Settings.Secure.getString(paramContext.getContentResolver(), "android_id");
        LoggerExt localLoggerExt = LOG;
        Object[] arrayOfObject = new Object[1];
        arrayOfObject[0] = sRawAndroidId;
        localLoggerExt.logInfo("Utils", "Secure.ANDROID_ID: andrdoidId - {0}", arrayOfObject);
      }
      String str = sRawAndroidId;
      return str;
    }
    finally
    {
    }
  }

  public static String getRawDeviceId(Context paramContext)
  {
    while (true)
    {
      try
      {
        String str1 = sRawDeviceId;
        if (str1 == null);
        try
        {
          if (ManifestValidator.customValidate(null, null, READ_PHONE_STATE_PERMISSION).getOptionalPermissions().isEmpty())
          {
            sRawDeviceId = ((TelephonyManager)paramContext.getSystemService("phone")).getDeviceId();
            LoggerExt localLoggerExt3 = LOG;
            Object[] arrayOfObject3 = new Object[1];
            arrayOfObject3[0] = sRawDeviceId;
            localLoggerExt3.logDebug("Utils", "TelephonyManager: deviceID - {0}", arrayOfObject3);
          }
          if (!isDeviceIdValid(sRawDeviceId))
          {
            i = 1;
            if ((i != 0) && (Build.VERSION.SDK_INT >= 9))
            {
              LOG.logDebug("Utils", "Trying to get serial of 2.3+ device...", new Object[0]);
              sRawDeviceId = SerialNumberUtil.getSerial();
              LoggerExt localLoggerExt2 = LOG;
              Object[] arrayOfObject2 = new Object[1];
              arrayOfObject2[0] = sRawDeviceId;
              localLoggerExt2.logDebug("Utils", "SERIAL: deviceID - {0}", arrayOfObject2);
              if (isDeviceIdValid(sRawDeviceId))
                break label254;
              i = 1;
            }
            if (i != 0)
            {
              sRawDeviceId = generateUniqueId(paramContext);
              LoggerExt localLoggerExt1 = LOG;
              Object[] arrayOfObject1 = new Object[1];
              arrayOfObject1[0] = sRawDeviceId;
              localLoggerExt1.logDebug("Utils", "Preferences: deviceID - {0}", arrayOfObject1);
            }
            String str2 = sRawDeviceId;
            return str2;
          }
        }
        catch (PackageManager.NameNotFoundException localNameNotFoundException)
        {
          LOG.logDebug("Utils", Log.getStackTraceString(localNameNotFoundException), new Object[0]);
          continue;
        }
      }
      finally
      {
      }
      int i = 0;
      continue;
      label254: i = 0;
    }
  }

  private static String getRawMac(Context paramContext)
  {
    try
    {
      if (sRawMac == null)
      {
        WifiManager localWifiManager = (WifiManager)paramContext.getSystemService("wifi");
        if (localWifiManager != null)
          sRawMac = localWifiManager.getConnectionInfo().getMacAddress();
      }
      if (sRawMac == null)
        sRawMac = "00:00:00:00:00:00";
      String str = sRawMac.toUpperCase();
      return str;
    }
    finally
    {
    }
  }

  public static float getScale(Context paramContext)
  {
    return paramContext.getResources().getDisplayMetrics().density;
  }

  public static int getScreenHeight(Context paramContext)
  {
    return paramContext.getResources().getDisplayMetrics().heightPixels;
  }

  public static int getScreenWidth(Context paramContext)
  {
    return paramContext.getResources().getDisplayMetrics().widthPixels;
  }

  public static Drawable getSkipImage(Context paramContext)
  {
    return getImage(paramContext, "VidButton_Close_%s.png", true);
  }

  public static Drawable getToolbarImage(Context paramContext)
  {
    return getImage(paramContext, "Bar_Gradient.png", false);
  }

  public static UserAgentInfo getUserAgent(Context paramContext)
  {
    UserAgentInfo localUserAgentInfo = new UserAgentInfo();
    localUserAgentInfo.setPlatformVersion(Build.VERSION.RELEASE);
    localUserAgentInfo.setDevice(Build.MODEL);
    localUserAgentInfo.setDeviceFamily(Build.BRAND);
    localUserAgentInfo.setOrmmaVersion("1.1");
    localUserAgentInfo.setMraidVersion("2.0");
    localUserAgentInfo.setRewardsVersion("2");
    setScreenInfo(paramContext, localUserAgentInfo);
    localUserAgentInfo.setMCC(getMccCode());
    localUserAgentInfo.setMNC(getMncCode());
    localUserAgentInfo.setCarrier(getCarrier());
    localUserAgentInfo.setWebUserAgent(getUserAgentString(paramContext));
    localUserAgentInfo.setApplicationVersion(getApplicationVersionName());
    localUserAgentInfo.setApplicationVersionCode(getApplicationVersionCode());
    return localUserAgentInfo;
  }

  public static String getUserAgentString(Context paramContext)
  {
    try
    {
      if (sUserWebClient == null)
      {
        WebView localWebView = new WebView(paramContext);
        sUserWebClient = localWebView.getSettings().getUserAgentString();
        localWebView.destroy();
      }
      String str = sUserWebClient;
      return str;
    }
    finally
    {
    }
  }

  public static Drawable getVisitSiteImage(Context paramContext)
  {
    return getImage(paramContext, "VidButton_More_%s.png", true);
  }

  public static void initCCSString(Context paramContext)
  {
    if (sCCSString == null)
    {
      TelephonyManager localTelephonyManager = (TelephonyManager)paramContext.getSystemService("phone");
      Object[] arrayOfObject = new Object[3];
      arrayOfObject[0] = localTelephonyManager.getNetworkOperator();
      arrayOfObject[1] = localTelephonyManager.getNetworkOperatorName();
      arrayOfObject[2] = getPhoneType(localTelephonyManager);
      sCCSString = MessageFormat.format("{0};{1};{2}", arrayOfObject);
    }
  }

  public static boolean isAdExpired(ResponseBean.ResponseData paramResponseData)
  {
    Long localLong = paramResponseData.getExpiresAfter();
    return (localLong != null) && (System.currentTimeMillis() > 20000L + localLong.longValue());
  }

  public static boolean isBanner(ResponseBean.ResponseData paramResponseData)
  {
    return paramResponseData.getDataType().equals(CreativeDataType.CreativeDataType_image.getValue());
  }

  private static boolean isDeviceIdValid(String paramString)
  {
    boolean bool;
    if (paramString == null)
    {
      LOG.logError("Utils", "Device id is null.", new Object[0]);
      bool = false;
    }
    while (true)
    {
      return bool;
      if ((paramString.length() != 0) && (!paramString.equals("000000000000000")) && (!paramString.equals("0")) && (!paramString.equals("unknown")));
      for (bool = true; !bool; bool = false)
      {
        LOG.logError("Utils", "Device id is empty or an emulator.", new Object[0]);
        return bool;
      }
    }
  }

  public static <K, V> boolean isIdenticalMap(Map<K, V> paramMap1, Map<K, V> paramMap2)
  {
    if (paramMap1.size() != paramMap2.size())
      return false;
    Iterator localIterator = paramMap1.keySet().iterator();
    while (localIterator.hasNext())
    {
      Object localObject = localIterator.next();
      if (!paramMap1.get(localObject).equals(paramMap2.get(localObject)))
        return false;
    }
    return true;
  }

  public static boolean isMraid(ResponseBean.ResponseData.AdType paramAdType)
  {
    if ((paramAdType == null) || (paramAdType.getExtendedProperty() == null))
      return false;
    return isMraidCreative(paramAdType.getExtendedProperty());
  }

  private static boolean isMraidCreative(Integer paramInteger)
  {
    return checkFlag(paramInteger, 2048);
  }

  public static boolean isOrmma(ResponseBean.ResponseData.AdType paramAdType)
  {
    if ((paramAdType == null) || (paramAdType.getExtendedProperty() == null))
      return false;
    return isOrmmaCreative(paramAdType.getExtendedProperty());
  }

  private static boolean isOrmmaCreative(Integer paramInteger)
  {
    return checkFlag(paramInteger, 1024);
  }

  public static boolean isRewards(Integer paramInteger)
  {
    CreativeDataType localCreativeDataType = getDataTypeByCode(paramInteger);
    return (localCreativeDataType == CreativeDataType.OfferWall) || (localCreativeDataType == CreativeDataType.CreativeDataType_offerpage);
  }

  public static boolean isScript(ResponseBean.ResponseData paramResponseData)
  {
    Integer localInteger = paramResponseData.getDataType();
    return (localInteger.equals(CreativeDataType.CreativeDataType_script.getValue())) || (localInteger.equals(CreativeDataType.CreativeDataType_redirect.getValue())) || (localInteger.equals(CreativeDataType.OfferWall.getValue())) || (localInteger.equals(CreativeDataType.CreativeDataType_offerpage.getValue()));
  }

  public static boolean isSdkAvailable(String paramString1, String paramString2)
  {
    try
    {
      Class.forName(paramString1);
      return true;
    }
    catch (ClassNotFoundException localClassNotFoundException)
    {
      LOG.logWarning(paramString2, "{0} lib is not included in classpath.", new Object[] { paramString1 });
    }
    return false;
  }

  public static boolean isSimpleText(ResponseBean.ResponseData paramResponseData)
  {
    return paramResponseData.getTextAdType().equals(TextAdType.TextAdType_mobile.getValue());
  }

  public static boolean isTextImage(ResponseBean.ResponseData paramResponseData)
  {
    return paramResponseData.getTextAdType().equals(TextAdType.TextAdType_mobileIcon.getValue());
  }

  public static boolean isThirdPartySDK(ResponseBean.ResponseData paramResponseData)
  {
    return "custom".equals(paramResponseData.getName());
  }

  public static boolean isValidRequestParam(String paramString)
  {
    return (paramString != null) && (paramString.trim().length() != 0);
  }

  public static boolean isVideo(ResponseBean.ResponseData paramResponseData)
  {
    return paramResponseData.getDataType().equals(CreativeDataType.CreativeDataType_video.getValue());
  }

  public static boolean isVideoUrl(String paramString)
  {
    return (paramString != null) && ((paramString.endsWith(".3gp")) || (paramString.endsWith(".mp4")));
  }

  public static void lowerCurrentThreadPriority()
  {
    if (!Thread.currentThread().equals(sApplicationContext.getMainLooper().getThread()))
      setCurrentThreadPriority(19);
  }

  public static HttpResponse makeGetRequest(String paramString)
    throws ClientProtocolException, IOException
  {
    return makeRequest(null, new HttpGet(paramString));
  }

  public static HttpResponse makeRequest(HttpHost paramHttpHost, HttpRequestBase paramHttpRequestBase)
    throws ClientProtocolException, IOException
  {
    HttpClient localHttpClient = getClient();
    if (sApplicationContext != null)
      paramHttpRequestBase.setHeader("User-Agent", getUserAgentString(sApplicationContext));
    if (paramHttpHost != null)
      return localHttpClient.execute(paramHttpHost, paramHttpRequestBase);
    return localHttpClient.execute(paramHttpRequestBase);
  }

  public static void mergeStringStringMaps(Map<String, String> paramMap1, Map<String, String> paramMap2)
  {
    if ((paramMap2 == null) || (paramMap1 == null) || (paramMap2.size() == 0));
    label135: 
    while (true)
    {
      return;
      Iterator localIterator1 = paramMap2.entrySet().iterator();
      while (true)
      {
        if (!localIterator1.hasNext())
          break label135;
        Map.Entry localEntry1 = (Map.Entry)localIterator1.next();
        String str1 = (String)localEntry1.getKey();
        String str2 = (String)localEntry1.getValue();
        Iterator localIterator2 = paramMap1.entrySet().iterator();
        if (localIterator2.hasNext())
        {
          Map.Entry localEntry2 = (Map.Entry)localIterator2.next();
          if (!str1.equalsIgnoreCase((String)localEntry2.getKey()))
            break;
          localEntry2.setValue(str2);
        }
      }
    }
  }

  public static Map<String, String> parseParams(String paramString)
  {
    HashMap localHashMap = new HashMap();
    if ((paramString != null) && (paramString.length() > 6))
    {
      String[] arrayOfString1 = paramString.split("\"");
      if (arrayOfString1.length == 3)
      {
        String[] arrayOfString2 = arrayOfString1[1].split(",");
        int i = arrayOfString2.length;
        for (int j = 0; j < i; j++)
        {
          String[] arrayOfString3 = arrayOfString2[j].split("=");
          if (arrayOfString3.length == 2)
            localHashMap.put(arrayOfString3[0], arrayOfString3[1]);
        }
      }
    }
    return localHashMap;
  }

  public static String reformatDateString(String paramString1, String paramString2, String paramString3)
  {
    if (paramString1 == null);
    while (true)
    {
      return null;
      SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat(paramString2);
      try
      {
        Date localDate2 = localSimpleDateFormat.parse(paramString1);
        localDate1 = localDate2;
        if (localDate1 == null)
          continue;
        return new SimpleDateFormat(paramString3).format(localDate1);
      }
      catch (ParseException localParseException)
      {
        while (true)
        {
          LOG.logThrowable("Utils", localParseException);
          Date localDate1 = null;
        }
      }
    }
  }

  public static float scale(int paramInt)
  {
    return scale(sApplicationContext, paramInt);
  }

  public static float scale(Context paramContext, int paramInt)
  {
    return paramContext.getResources().getDisplayMetrics().density * paramInt;
  }

  public static Integer scaleToDip(Integer paramInteger)
  {
    if (paramInteger == null)
      return paramInteger;
    float f = sApplicationContext.getResources().getDisplayMetrics().density;
    return Integer.valueOf((int)(paramInteger.intValue() / f));
  }

  public static void setApplicationContext(Context paramContext)
  {
    if (sApplicationContext == null)
      sApplicationContext = paramContext.getApplicationContext();
  }

  @TargetApi(16)
  public static void setBackgroundDrawable(View paramView, Drawable paramDrawable)
  {
    if (Build.VERSION.SDK_INT >= 16)
    {
      paramView.setBackground(paramDrawable);
      return;
    }
    paramView.setBackgroundDrawable(paramDrawable);
  }

  public static void setCurrentThreadPriority(int paramInt)
  {
    try
    {
      Process.setThreadPriority(paramInt);
      return;
    }
    catch (SecurityException localSecurityException)
    {
    }
    catch (IllegalArgumentException localIllegalArgumentException)
    {
    }
  }

  @TargetApi(11)
  public static void setHardwareAcceleration(View paramView, boolean paramBoolean)
  {
    if (Build.VERSION.SDK_INT >= 11)
    {
      if (!paramBoolean)
      {
        paramView.setLayerType(1, null);
        return;
      }
      paramView.setLayerType(2, null);
      return;
    }
    LOG.logDebug("Utils", "This device doesn't support hardware acceleration control.", new Object[0]);
  }

  private static void setScreenInfo(Context paramContext, UserAgentInfo paramUserAgentInfo)
  {
    DisplayMetrics localDisplayMetrics = new DisplayMetrics();
    ((Activity)paramContext).getWindowManager().getDefaultDisplay().getMetrics(localDisplayMetrics);
    paramUserAgentInfo.setScreenResolution(localDisplayMetrics.widthPixels + "x" + localDisplayMetrics.heightPixels);
    String str = "";
    if (Build.VERSION.SDK_INT < 4)
      if (localDisplayMetrics.density < 1.0F)
        str = "Low";
    while (true)
    {
      paramUserAgentInfo.setDensity(str);
      paramUserAgentInfo.setAndroidDensityId(localDisplayMetrics.densityDpi);
      return;
      if (localDisplayMetrics.density == 1.0F)
      {
        str = "Medium";
      }
      else if (localDisplayMetrics.density > 1.0F)
      {
        str = "High";
        continue;
        str = DensityDpiProvider.getDisplayDensity(localDisplayMetrics);
      }
    }
  }

  private static void setScreenInfo(Context paramContext, ServerRequestBean paramServerRequestBean)
  {
    DisplayMetrics localDisplayMetrics = new DisplayMetrics();
    ((Activity)paramContext).getWindowManager().getDefaultDisplay().getMetrics(localDisplayMetrics);
    paramServerRequestBean.setScreenResolution(localDisplayMetrics.widthPixels + "x" + localDisplayMetrics.heightPixels);
    String str = "";
    if (Build.VERSION.SDK_INT < 4)
      if (localDisplayMetrics.density < 1.0F)
        str = "Low";
    while (true)
    {
      paramServerRequestBean.setDensity(str);
      return;
      if (localDisplayMetrics.density == 1.0F)
      {
        str = "Medium";
      }
      else if (localDisplayMetrics.density > 1.0F)
      {
        str = "High";
        continue;
        str = DensityDpiProvider.getDisplayDensity(localDisplayMetrics);
      }
    }
  }

  public static String sha1(String paramString1, String paramString2)
  {
    try
    {
      MessageDigest localMessageDigest = MessageDigest.getInstance("SHA-1");
      localMessageDigest.update(paramString1.getBytes());
      String str = bytesToString(localMessageDigest.digest());
      return str;
    }
    catch (NoSuchAlgorithmException localNoSuchAlgorithmException)
    {
      LOG.logWarning("Utils", "SHA-1 algorithm implementation is not found on device!", new Object[0]);
    }
    return paramString2;
  }

  public static List<String> shuffle(List<String> paramList)
  {
    return shuffle(paramList, null);
  }

  public static List<String> shuffle(List<String> paramList, String paramString)
  {
    ArrayList localArrayList = new ArrayList(paramList);
    Collections.shuffle(localArrayList);
    if (paramString != null)
      localArrayList.add(0, paramString);
    return localArrayList;
  }

  public static String toJson(Object paramObject)
  {
    return JSON_PROCESSOR.toJson(paramObject);
  }

  public static void writeToOutput(InputStream paramInputStream, OutputStream paramOutputStream)
    throws IOException
  {
    byte[] arrayOfByte = new byte[4096];
    while (true)
    {
      int i = paramInputStream.read(arrayOfByte);
      if (i == -1)
        break;
      paramOutputStream.write(arrayOfByte, 0, i);
    }
  }

  public static final class DebugWrapper
  {
    private static final int BYTES_IN_KB = 1024;
    private final String mLogTag;

    private DebugWrapper(String paramString)
    {
      this.mLogTag = paramString;
    }

    public static DebugWrapper getDebugger(String paramString)
    {
      return new DebugWrapper(paramString);
    }

    public void logAll()
    {
      logNativeHeap();
      logJavaHeap();
    }

    public void logJavaHeap()
    {
      if (Constants.IS_DEBUG_MODE)
      {
        Runtime localRuntime = Runtime.getRuntime();
        Object[] arrayOfObject1 = new Object[1];
        arrayOfObject1[0] = Long.valueOf(localRuntime.maxMemory() / 1024L);
        String str1 = String.format(" - Dalvik max heap size: %d KB", arrayOfObject1);
        Utils.LOG.logDebug(this.mLogTag, str1, new Object[0]);
        Object[] arrayOfObject2 = new Object[1];
        arrayOfObject2[0] = Long.valueOf(localRuntime.totalMemory() / 1024L);
        String str2 = String.format(" - Dalvik heap size: %d KB", arrayOfObject2);
        Utils.LOG.logDebug(this.mLogTag, str2, new Object[0]);
      }
    }

    public void logNativeHeap()
    {
      if (Constants.IS_DEBUG_MODE)
      {
        Object[] arrayOfObject1 = new Object[1];
        arrayOfObject1[0] = Long.valueOf(Debug.getNativeHeapSize() / 1024L);
        String str1 = String.format(" - Native heap size: %d KB", arrayOfObject1);
        Utils.LOG.logDebug(this.mLogTag, str1, new Object[0]);
        Object[] arrayOfObject2 = new Object[1];
        arrayOfObject2[0] = Long.valueOf(Debug.getNativeHeapAllocatedSize() / 1024L);
        String str2 = String.format(" - Native heap allocated size: %d KB", arrayOfObject2);
        Utils.LOG.logDebug(this.mLogTag, str2, new Object[0]);
      }
    }
  }

  private static class FlushedInputStream extends FilterInputStream
  {
    public FlushedInputStream(InputStream paramInputStream)
    {
      super();
    }

    public long skip(long paramLong)
      throws IOException
    {
      long l2;
      for (long l1 = 0L; ; l1 += l2)
      {
        if (l1 < paramLong)
        {
          l2 = this.in.skip(paramLong - l1);
          if (l2 != 0L)
            continue;
          if (read() >= 0);
        }
        else
        {
          return l1;
        }
        l2 = 1L;
      }
    }
  }
}

/* Location:           E:\android\Toy Defense 2_dex2jar.jar
 * Qualified Name:     com.burstly.lib.util.Utils
 * JD-Core Version:    0.6.2
 */